<template>
  <div :id="`${videoId}Container`" class='smv-container' :style="{height:`${videoHeight}px`}" >
    <div class="smv-video-wrapper" :style="{backgroundImage:`${currentTime==0?`url('${poster}')`:'none'}`}">
      <video class="smv-video" :style="{opacity:currentTime>0?1:0}"  :id="videoId"
             playsinline="true"
             webkit-playsinline="true"
             x-webkit-airplay="allow"
             airplay="allow"
             x5-video-player-type="h5"
             x5-video-player-fullscreen="false"
             @click="videoClick">
<!--        <source :src="videoSrc" v-if="videoSrc">-->
      </video>
      <div class="smv-video-bar" v-show="showVideoBar">
        <div class="smv-video-time">{{getTimeBySecond(currentTime)}}</div>
        <div class="smv-video-slider">
          <progress class="smv-progress-bar" :value="progressValue" max="100"></progress>
          <input type="range" value="0" class="smv-seek-bar" @change="changeProgress" v-model="progressValue"></div>
        <div class="smv-video-time"><span class="video-time-total">{{getTimeBySecond(totalTime)}}</span></div>
        <div class="smv-video-speed-container">
          <div v-show="showSpeedSetting" class="smv-video-speed-list">
            <div class="smv-video-speed-item" :class="{active:item==currentSpeed}" v-for="item in speedList" @click="chooseSpeed(item)">{{item+""}}X</div>
          </div>
          <button class="smv-video-speed" v-if="speed && speedList.length>0" @click="showSpeedSetting=!showSpeedSetting">{{speedText}}</button>
        </div>
        <button class="smv-video-fullscreen" @click="fullScreen" :class="{'exit-fullscreen':isFullScreen}"
                ></button>
      </div>
      <div class="smv-video-play-icon" :class="{off:hidePlayIcon,'loading':isLoading}" @click="play()"></div>
      <div class="smv-video-error" v-if="videoError"><span>视频异常，请刷新</span></div>
    </div>
  </div>
</template>

<script>
  // import './mobilevideo.css'
  import Hls from 'ssit-hls'

  const userAgent = navigator.userAgent.toLowerCase();

  export default {
    name: "ssit-mobile-video",
    inheritAttrs: false,
    props: {
      src: {
        type: String,
        default() {
          return ""
        }
      },
      poster: {
        type: String,
        default() {
          return ""
        }
      },
      videoId: {
        type: String,
        default() {
          return "ssitMobileVideo_" + Math.round(Math.random() * 10000)
        }
      },
      startTime: {
        type: Number,
        default() {
          return 0;
        }
      },
      speed: {
        type: Boolean,
        default() {
          return true;
        }
      },
      speedList: {
        type: Array,
        default() {
          return ["1.0", "1.25", "1.5", "2.0"]
        }
      },
      keepVideoRate:{
        type:Boolean,
        default(){
          return true;
        }
      },
      queryStaticUrl:{
        type:Boolean,
        default(){
          return true;
        }
      }
    },
    data() {
      return {
        realSrc:"",
        video: null,//video的dom元素
        hlsObj: null,
        videoHeight: document.documentElement.clientWidth*9/16||210,
        isFullScreen: false,
        isPause: true,
        isLoading: false,
        showVideoBar: true,
        progressValue:0,
        currentTime:0,
        totalTime:0,
        currentSpeed:1,
        showSpeedSetting:false,
        videoError:false
      }
    },
    computed: {
      videoSrc(){
        if(this.isIos){
          return this.src;
        }else{
          return this.realSrc;
        }
      },
      setStartTimeEvent() {
        return "timeupdate";
      },
      hidePlayIcon() {
        console.log(this.isPause,this.isLoading)
        return !this.isPause || this.isLoading
      },
      isQQBrowser() {
        if (userAgent.indexOf("mqqbrowser") > -1) {
          return true;
        }
        return false;
      },
      isMobile() {
        return this.isAndroid || this.isIos
      },
      // 判断安卓
      isAndroid() {
        if (userAgent.indexOf("android") > -1 || userAgent.indexOf("linux") > -1) {
          return true;
        }
        return false;
      },
      // 判断设备为 ios
      isIos() {
        if (userAgent.indexOf("iphone") > -1 || userAgent.indexOf("ios") > -1) {
          return true;
        }
        return false;
      },
      speedText(){
        return this.currentSpeed!=1?`${this.currentSpeed}X`:'倍速'
      }
    },
    created() {
    },
    mounted() {
      this.video = document.getElementById(`${this.videoId}`);
      let videoContainer = document.getElementById(`${this.videoId}Container`)
      //第一个参数为视频地址，第二个为video的dom元素
      // this.hlsObj = Hls.hlsPlay(this.src, this.video);
      this.srcChange()
      this.$emit("init-finish", this.video);
      this.$nextTick(()=>{
        setTimeout(()=>{
          this.videoHeight = (videoContainer.clientWidth / 1.785).toFixed(2);
        },200)
      })
      window.onresize = () => {
        this.resetVideoSize()
      }
      this.addVideoEventListener();
      this.autoHideControls()
    },
    methods: {
      resetVideoSize(){
        let videoContainer = document.getElementById(`${this.videoId}Container`)
        this.videoHeight = (videoContainer.clientWidth / 1.785).toFixed(2);
        this.$forceUpdate();
      },
      addVideoEventListener(){
        if(this.video){
          this.video.addEventListener("waiting",this.waitingEvent);
          this.video.addEventListener("pause",this.pauseEvent);
          this.video.addEventListener("seeking",this.seekingEvent);
          this.video.addEventListener("seeked",this.seekedEvent);
          this.video.addEventListener("timeupdate",this.timeupdateEvent);
          this.video.addEventListener("loadedmetadata",this.loadedmetadataEvent);
          this.video.addEventListener("error",this.errorEvent);
          if(this.video.duration){
            this.totalTime = this.video.duration;
          }
          this.setFullScreenListener();
        }
      },
      sentFullScreenMsg(){
        console.log("sentFullScreenMsg",this.video.id)
        let videoFullScreenMsg = localStorage.getItem("videoFullScreen");
        if(videoFullScreenMsg&&videoFullScreenMsg.indexOf("http")==-1&&videoFullScreenMsg.indexOf(":")>=0&&this.video.videoWidth>this.video.videoHeight){
          console.log("进入全屏",videoFullScreenMsg)
          location.href=localStorage.getItem("videoFullScreen")
        }
      },
      sendExitFullScreenMsg(){
        console.log("sendExitFullScreenMsg",this.video.id)
        let videoExitFullScreenMsg = localStorage.getItem("videoExitFullScreen");
        if(videoExitFullScreenMsg&&videoExitFullScreenMsg.indexOf("http")==-1&&videoExitFullScreenMsg.indexOf(":")>=0&&this.video.videoWidth>this.video.videoHeight){
          console.log("退出全屏",videoExitFullScreenMsg)
          location.href=localStorage.getItem("videoExitFullScreen")
        }
        if(videoExitFullScreenMsg&&videoExitFullScreenMsg.indexOf("http")==-1&&videoExitFullScreenMsg.indexOf(":")>=0&&window.currentFullScreenElement){
          console.log("scrollIntoView",window.currentFullScreenElement.id)
          window.currentFullScreenElement.scrollIntoView({block:"center"})
        }
      },
      fullScreenChange(event){
        if(document.fullscreenElement){
          if(document.fullscreenElement.id!=this.video.id){
            return;
          }
          window.currentFullScreenElement = document.fullscreenElement;
          this.sentFullScreenMsg();
        }else{
          if(window.currentFullScreenElement.id!=this.video.id){
            return;
          }
          this.sendExitFullScreenMsg();
        }
      },
      setFullScreenListener(){
        let _this = this;
        //监听全屏切换，目前这个只能对安卓生效
        document.addEventListener("fullscreenchange",this.fullScreenChange)
        this.video.addEventListener("webkitbeginfullscreen",()=>{
          window.currentFullScreenElement  = this.video;
          this.sentFullScreenMsg();
        })
        this.video.addEventListener("webkitendfullscreen",this.sendExitFullScreenMsg)
      },
      videoClick(){
        if(!this.showVideoBar){
          this.showVideoBar = true;
          return;
        }
        //视频处于播放状态，进行暂停
        if(this.video && this.video.duration>0 && !this.video.paused){
          this.video.pause();
          this.isPause = true;
        }
      },
      setStartTime() {
        if(this.video.currentTime>0){
          this.video.removeEventListener(this.setStartTimeEvent, this.setStartTime)
        }
        if (this.startTime > 0 && this.startTime < this.video.duration) {
          this.video.currentTime = this.startTime;
        }

      },
      fullScreen() {
        if(this.isMobile && this.currentTime == 0){
          return;
        }
        let ele = this.isMobile ? this.video : this.video.parentElement;
        if (!this.isFullScreen) {
          this.enterFullScreen(ele)
        } else if (!this.isMobile) {
          // exit full-screen
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
          }
          this.isFullScreen = false;
        }
      },
      enterFullScreen(ele){
        if (ele.requestFullscreen) {
          ele.requestFullscreen();
        } else if (ele.webkitRequestFullscreen) {
          ele.webkitRequestFullscreen();
        } else if (ele.mozRequestFullScreen) {
          ele.mozRequestFullScreen();
        } else if (ele.msRequestFullscreen) {
          ele.msRequestFullscreen();
        } else if (ele.webkitEnterFullScreen) {
          ele.webkitEnterFullScreen();
        } else {
          console.log("无法全屏")
          return false;
        }
        if(!this.isMobile){
          this.isFullScreen = true;
        }
        return true;
      },
      autoHideControls() {
        let _this = this;
        let hideControl = () => {
          if (_this.video && !_this.video.paused) {
            _this.showVideoBar = false;
            _this.showSpeedSetting = false;
          }
        };
        let timerId = setTimeout(hideControl, 10000);
        let parentElement = this.video.parentElement;
        ["mousemove", "touchmove","click"].forEach((type) => {
          this.video.addEventListener(type, (event) => {
            if (timerId) {
              clearInterval(timerId);
            }
            _this.showVideoBar = true;
            timerId = setTimeout(hideControl, 10000);
          });
        });
      },
      play(){
        if(this.video && this.video.paused){
          this.video.play();
        }
      },
      waitingEvent(){
        this.isLoading = true;
        console.log("waitingEvent")
      },
      pauseEvent(){
        this.isPause = true;
        console.log("pauseEvent")
      },
      seekingEvent(){
        this.isLoading = true;
        console.log("seekingEvent")
      },
      seekedEvent(){
        if(this.video.currentTime != this.video.duration){
          this.video.play();
        }
        console.log("seekedEvent")
      },
      changeProgress(){
        let time = this.video.duration * (this.progressValue / 100);
        if(isNaN(time)){
          time = 0;
        }
        this.video.currentTime = time;

      },
      timeupdateEvent(){
        let val = (100 / this.video.duration) * this.video.currentTime;
        if(isNaN(val)){
          val = 0;
        }
        this.progressValue = val;
        //更新当前时间
        this.currentTime = this.video.currentTime;
        this.totalTime = this.video.duration;
        if(this.currentTime>0){
          this.isPause = false;
          this.isLoading = false;
          this.videoError = false;
        }
      },
      loadedmetadataEvent(){
        this.totalTime = this.video.duration;
        console.log("loadedmetadataEvent")
      },
      errorEvent(e){
        if(this.videoSrc&&this.videoSrc!="undefined"&&this.videoSrc!="null"){
          this.videoError = true;
        }
        console.log("errorEvent:",this.videoSrc,e)
      },
      chooseSpeed(speed){
        if(this.currentSpeed == speed){
          return;
        }
        this.currentSpeed = speed;
        this.video.playbackRate = speed;
        this.showSpeedSetting = false;
      },
      getTimeBySecond(s){
        if(isNaN(s)){
          s = 0;
        }
        let hour = parseInt(""+(s / 3600));
        let minute = parseInt(""+((s/60) % 60));
        let second = parseInt(""+(s % 60));
        let result = (hour > 0 ?((hour < 10 ? "0" + hour:hour) + ":") : "") + (minute < 10 ? "0" + minute:minute) + ":" + (second < 10 ? "0" + second:second);
        return result;
      },
      initVideoSpeed(){
        this.video.playbackRate = this.currentSpeed;
        if(this.video.currentTime>0){
          this.video.removeEventListener("timeupdate",this.initVideoSpeed)
        }
      },
      initVideoInfo(){
        this.hlsObj = Hls.hlsPlay(this.videoSrc, this.video);
        this.currentTime = 0;
        this.totalTime = 0;
        this.isPause = true;
        this.isLoading = false;
        this.videoError = false;
        if(this.keepVideoRate){
          this.video.addEventListener("timeupdate",this.initVideoSpeed);
        }else{
          this.video.playbackRate = 1;
          this.currentSpeed = 1;
        }
        this.video.addEventListener(this.setStartTimeEvent, this.setStartTime)
        console.log("currentSpeed=",this.currentSpeed)
      },
      srcChange(){
        let _this = this;
        if (this.hlsObj) {
          this.hlsObj.destroy();
        }
        if(this.src.indexOf("receive/EZ-NFS")>=0&&this.queryStaticUrl&&!this.isIos){
          ajax({
            url:this.src.replace("/receive/","/receiveStaticUrl/"),
            type:'GET',
            dataType:'json',
            success:function(response,xml){
              debugger
              //请求成功后执行的代码
              if(response.code==200){
                _this.realSrc = response.data;
              }else{
                _this.realSrc = _this.src;
              }
              _this.initVideoInfo();
            },
            error:function(status){
              //失败后执行的代码
              _this.realSrc = _this.src;
              _this.initVideoInfo();
            }
          })
        }else{
          this.realSrc = this.src;
          this.initVideoInfo();
        }
      }
    },
    watch: {
      src() {
        this.srcChange();
      }
    }
  }
  function ajax(options){
    options=options||{};
    options.type=(options.type||'GET').toUpperCase();
    options.dataType=options.dataType||'json';
    let params=formatParams(options.data);

    //创建-第一步
    let xhr;
    //非IE6
    if(window.XMLHttpRequest){
      xhr=new XMLHttpRequest();
    }else{
      //ie6及其以下版本浏览器
      xhr=ActiveXObject('Microsoft.XMLHTTP');
    }

    //接收-第三步
    xhr.onreadystatechange=function(){
      if(xhr.readyState==4){
        let status=xhr.status;
        if(status>=200&&status<300){
          let result;
          try{
            result = JSON.parse(xhr.responseText);
          }catch(e){
            result = xhr.responseText
          }
          options.success&&options.success(result,xhr.responseXML);
        }else{
          options.error&&options.error(status);
        }
      }
    }

    //连接和发送-第二步
    if(options.type=='GET'){
      xhr.open('GET',options.url+'?'+params,true);
      xhr.send(null);
    }else if(options.type=='POST'){
      xhr.open('POST',options.url,true);
      //设置表单提交时的内容类型
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.send(params);
    }
  }
  function formatParams(data){
    let arr=[];
    for(let name in data){
      arr.push(encodeURIComponent(name)+'='+encodeURIComponent(data[name]));
    }
    return arr.join('&');
  }
</script>
<style lang="scss">
  @import "mobilevideo";
</style>
